/**
 * copyright (c) 2017-2022
 * https://www.fengling.cn/
 * 
 * 初始化Bundle模板
 * zengbinsi
 * 2022-01-26
 */


import path from 'path';
import {exec} from 'child_process';
import pathUtil from '../libs/utils/path-utils';
import fileUtil from '../libs/utils/file-utils';
import { callSequence } from '../libs/utils/function-call-seq';

const srcPath = pathUtil.pathTemplateAssets;
const dstPath = pathUtil.pathAssets;


const initDir = (callback?: Function)=>{
    const dir = path.join(dstPath, 'bundles');
    console.log('[tool-box]创建目录', dir);
    pathUtil.mkPathSync(dir);
    callback && callback();
};

const updateMeta = (filePath: string)=>{
    try {
        console.log('update meta file:', filePath);
        let data: any = fileUtil.readFileSync(filePath);
        if (data) {
            data = JSON.parse(data);
            data.userData && (data.userData.isBundle = true);
            data = JSON.stringify(data, null, "\t");
        }
        fileUtil.writeFileSync(filePath, data);
    } catch (error) {
        console.error(error);
    }
};


export const initBundle = (bundleName: string, callback?: Function)=>{
    console.log('[tool-box]正在创建bundle...');

    return callSequence([initDir, (cb?: Function) => {
        const src = path.join(srcPath, 'bundles', 'bundle-template');
        const dst = path.join(dstPath, 'bundles');
        const sh = `cp -rf ${src} ${dst}`;

        exec(sh, async (err, stdout, stderr) => {
            if (err || stderr) { return console.log('[tool-box]创建bundle失败', err, stderr); }

            fileUtil.rename(path.join(dstPath, 'bundles', 'bundle-template'), path.join(dstPath, 'bundles', bundleName));
            try {
                await pathUtil.refreshAsset(`db://assets/bundles/${bundleName}`);
                console.log('[tool-box]', '创建bundle结束!');
                cb && cb();
            } catch (error) {
                console.error('[tool-box]error:', error);
            }
        });
    }, callback]);
};